import {
  BVID_CONCLUSION_KEY,
  extractBvid,
  getBvidSubtitle,
  insertVideoByBvid,
} from "@/utils/bilibili";
import { getBvidComments } from "@/utils/bilibili/comments";
import { stringToPDFDownload } from "@/utils/pdf.ts";
import { Button, Form, Input, message, Modal, Space, Switch, Tooltip } from "antd";
import deepseek, {
  BVID_SUBTITLE_MAP_DEEPSEEK_CHAT_ID,
} from "@/utils/deepseek/index";
import _ from "lodash";
import tongyi, { BVID_SUBTITLE_MAP_TONGYI_CHAT_ID } from "@/utils/tongyi";
import doubao, { BVID_SUBTITLE_MAP_DOUBAO_CHAT_ID } from "@/utils/doubao";
import { useSetState } from "ahooks";
import { QuestionOutlined } from "@ant-design/icons";

const PROMPT_KEY = "prompt";

export const useOperation = () => {
  const [modalForm] = Form.useForm();
  const [bvidList, setList] = useState<any>([]);
  const [setting, setSetting] = useSetState({
    variable: false,
    prompt: localStorage.getItem(PROMPT_KEY) || "总结归纳文章的关键信息:",
  });
  // 下载评论区数据
  const handleDownloadComments = async (bvid: string, title: string) => {
    const hide = message.loading("正在获取评论区数据", 0);
    const c = await getBvidComments(bvid);
    hide();
    stringToPDFDownload(JSON.stringify(c), title);
  };

  const addByBvid = async (_bvid: string) => {
    const bvid = extractBvid(_bvid);
    if (!bvid) {
      message.error("请输入正确的BV号");
      return;
    }
    const hide = message.loading("正在获取视频信息", 0);
    await insertVideoByBvid(bvid);
    hide();
    refreshBvidList();
  };

  const refreshBvidList = async () => {
    const result = await chrome.storage.local.get([BVID_CONCLUSION_KEY]);
    let _bvidList = result[BVID_CONCLUSION_KEY];
    _bvidList = _.map(_bvidList, (item) => {
      const page = _.map(item.pages || [], (page) => ({
        ...page,
        title: page.part,
        bvid: item.bvid,
        isLeaf: true,
      }));

      return {
        ...item,
        pages: page.length > 1 ? page : undefined,
      };
    });
    setList(_bvidList || []);
  };

  const sendDeepSeekSummary = async (bvid: string, cid?: string) => {
    const result = await chrome.storage.local.get([
      BVID_SUBTITLE_MAP_DEEPSEEK_CHAT_ID,
    ]);
    const chatIdMap = result?.[BVID_SUBTITLE_MAP_DEEPSEEK_CHAT_ID] ?? {};
    const chatId = chatIdMap?.[bvid];
    if (chatId) {
      window.open(`https://chat.deepseek.com/a/chat/s/${chatId}`, "_blank");
      return;
    }
    const prompt = await getBvidSubtitle(bvid, cid);
    const hide = message.loading("请求中..", 0);
    const chat_session_id = await deepseek.createChat();
    chatIdMap[bvid] = chat_session_id;

    await deepseek.completeChat({
      chat_session_id,
      parent_message_id: null,
      prompt,
      thinking_enabled: false,
      search_enabled: false,
      ref_file_ids: [],
    });
    chrome.storage.local.set({
      [BVID_SUBTITLE_MAP_DEEPSEEK_CHAT_ID]: chatIdMap,
    });
    hide();
    message.success("请求成功");
  };

  const sendTongyiSummary = async (bvid: string, cid?: string) => {
    const result = await chrome.storage.local.get([
      BVID_SUBTITLE_MAP_TONGYI_CHAT_ID,
    ]);
    const chatIdMap = result?.[BVID_SUBTITLE_MAP_TONGYI_CHAT_ID] ?? {};
    const key = _.compact([bvid, cid]).join("-");
    const chatId = chatIdMap?.[key];
    if (chatId) {
      window.open(
        `https://www.tongyi.com/qianwen?sessionId=${chatId}`,
        "_blank"
      );
      return;
    }
    const prompt = await getBvidSubtitle(bvid, cid);
    const hide = message.loading("请求中..", 0);
    tongyi.createChat(prompt, setting.prompt);

    message.success("请求成功");

    hide();
  };

  const sendDoubaoSummary = async (bvid: string, cid?: string) => {
    const result = await chrome.storage.local.get([
      BVID_SUBTITLE_MAP_DOUBAO_CHAT_ID,
    ]);
    const chatIdMap = result?.[BVID_SUBTITLE_MAP_DOUBAO_CHAT_ID] ?? {};
    const key = _.compact([bvid, cid]).join("-");
    const chatId = chatIdMap?.[key];
    if (chatId) {
      window.open(`https://www.doubao.com/chat/${chatId}`, "_blank");
      return;
    }
    const prompt = await getBvidSubtitle(bvid, cid);
    const hide = message.loading("请求中..", 0);
    doubao.createChat(prompt, setting.prompt);
    message.success("请求成功");
    // const res = await doubao.createChat(prompt);
    // if (res?.status === 500) {
    //   message.error("请求失败");
    // } else {
    //   message.success("请求成功");
    // }
    hide();
  };

  const onOpenConfigModal = useCallback(async () => {
    try {
      modalForm.setFieldsValue(setting);

      const modal = Modal.confirm({
        icon: null,
        title: "配置",
        width: "100%",
        content: (
          <Form form={modalForm}>
            <Form.Item label={<span>变量模式 <Tooltip title="开启后，请在提示词中使用 {{DOCUMENT}} 作为替换的占位符"><QuestionOutlined /></Tooltip></span>} name="variable" valuePropName="checked">
              <Switch />
            </Form.Item>
            <Form.Item label="提示词:" name="prompt">
              <Input.TextArea autoSize={{ minRows: 3 }} />
            </Form.Item>
          </Form>
        ),
        footer: (
          <Space style={{ width: "100%", justifyContent: "end" }}>
            <Button
              onClick={() => {
                modalForm.resetFields();
                modal.destroy();
              }}
            >
              取消
            </Button>
            <Button
              onClick={() => {
                modalForm
                  .validateFields()
                  .then((values) => {
                    setSetting(values);
                    chrome.storage.local.set({
                      [PROMPT_KEY]: values,
                    });
                    modal.destroy();
                  })
                  .finally(() => {
                    modalForm.resetFields();
                  });
              }}
              type="primary"
            >
              提交
            </Button>
          </Space>
        ),
      });
    } catch (error) {
      console.log("error", error);
    }
  }, [modalForm, setting]);


  useEffect(() => {
    chrome.storage.local.get([PROMPT_KEY]).then((res: any) => {
      const config = res[PROMPT_KEY] || {};
      setSetting(config);
    });
  }, []);

  return {
    sendDeepSeekSummary,
    sendDoubaoSummary,
    sendTongyiSummary,
    handleDownloadComments,
    addByBvid,
    bvidList,
    setList,
    refreshBvidList,
    onOpenConfigModal,
  };
};
